/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/ccjzxyxt">ccjzxyxt</a> All rights reserved.
 */
package cn.net.dckj.modules.biz.web;

import cn.net.dckj.common.config.Global;
import cn.net.dckj.common.persistence.JsonData;
import cn.net.dckj.common.persistence.Page;
import cn.net.dckj.common.utils.HttpClientUtil;
import cn.net.dckj.common.utils.StringUtils;
import cn.net.dckj.common.web.BaseController;
import cn.net.dckj.modules.biz.common.EducationUtils;
import cn.net.dckj.modules.biz.entity.BizTeacherTimetable;
import cn.net.dckj.modules.biz.entity.BizVmApply;
import cn.net.dckj.modules.biz.entity.ClassTime;
import cn.net.dckj.modules.biz.service.BizTeacherTimetableService;
import cn.net.dckj.modules.biz.service.BizVmApplyService;
import cn.net.dckj.modules.biz.service.ClassTimeService;
import cn.net.dckj.modules.cms.entity.Site;
import cn.net.dckj.modules.cms.utils.CmsUtils;
import cn.net.dckj.modules.sys.entity.Menu;
import cn.net.dckj.modules.sys.entity.User;
import cn.net.dckj.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 虚拟机使用申请Controller
 *
 * @author hqj
 * @version 2019-04-20
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizVmApply")
public class BizVmApplyController extends BaseController {

    @Autowired
    private BizVmApplyService bizVmApplyService;
    @Autowired
    private ClassTimeService classTimeService;

    @ModelAttribute
    public BizVmApply get(@RequestParam(required = false) String id) {
        BizVmApply entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = bizVmApplyService.get(id);
        }
        if (entity == null) {
            entity = new BizVmApply();
        }
        return entity;
    }

    @RequiresPermissions("biz:bizVmApply:view")
    @RequestMapping(value = {"list", ""})
    public String list(BizVmApply bizVmApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        //增加数据权限控制，admin查询所有数据，其他用户只查询本人数据
        User user = UserUtils.getUser();
        if (!user.isAdmin()) {
            if (bizVmApply.getCreateBy() == null) {
                bizVmApply.setCreateBy(user);
            } else {
                if (StringUtils.isBlank(bizVmApply.getCreateBy().getId())) {
                    bizVmApply.setCreateBy(user);
                }
            }
        }
        Page<BizVmApply> page = bizVmApplyService.findPage(new Page<BizVmApply>(request, response), bizVmApply);
        model.addAttribute("page", page);
        String origin = request.getParameter("origin");
        if (("front").equals(origin)) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            Menu menu = UserUtils.getNavMenu("myapply");
            model.addAttribute("menu", menu);
            String tabIndex = request.getParameter("tabIndex");
            model.addAttribute("tabIndex", tabIndex);
            return "modules/cms/front/themes/basic/grzx_myApply";
        } else {
            return "modules/biz/bizVmApplyList";
        }
    }

    @RequiresPermissions("biz:bizVmApply:view")
    @RequestMapping(value = "form")
    public String form(BizVmApply bizVmApply, Model model, HttpServletRequest request) {
        model.addAttribute("bizVmApply", bizVmApply);
        String op = request.getParameter("op");
        if (StringUtils.isNotEmpty(op)) {
            if (op.equals("2")) { // 审核操作
                return "modules/biz/bizVmApplyFormCheck";
            } else { // 查看操作
                return "modules/biz/bizVmApplyFormView";
            }
        } else { // 查看操作
            return "modules/biz/bizVmApplyFormView";
        }
    }

    @RequiresPermissions("biz:bizVmApply:view")
    @RequestMapping(value = "form/json")
    @ResponseBody
    public JsonData formJson(BizVmApply bizVmApply, Model model, HttpServletRequest request) {
        JsonData jsonData = new JsonData();
        jsonData.setSuccess(true).setData(bizVmApply).setTotalCount(1);
        return jsonData;
    }

    @RequiresPermissions("biz:bizVmApply:edit")
    @RequestMapping(value = "save")
    public String save(BizVmApply bizVmApply, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        if (!beanValidator(model, bizVmApply)) {
            return form(bizVmApply, model, request);
        }
        String op = request.getParameter("op");
        if ("1".equals(op)) { // 申请操作
            bizVmApply.setCheckFlag("1");
            // 自动进行审核判断，如果上课时间则状态不通过，记录原因
            // =====配置需要查询条件=====
            ClassTime classTime = new ClassTime();
            classTime.setCourseBeginDate(bizVmApply.getApplyStartDate());
            classTime.setCourseEndDate(bizVmApply.getApplyEndDate());
            List<ClassTime> classTimeList = classTimeService.findList(classTime);
            if (classTimeList != null && classTimeList.size() > 0) {
                bizVmApply.setCheckFlag("3"); // 3 审核未通过
                bizVmApply.setCheckReason("该申请使用时间内有课，请换一个使用时间！");
                bizVmApply.setCheckId("sys");
                bizVmApply.setCheckName("系统");
                bizVmApply.setCheckDate(new Date());
            } else {
                // 自动进行审核判断，如果目前资源不足，状态不通过，记录原因；否则分配资源，状态通过（暂不做，进一步确认需求）
                // 获取泽塔登录和创建虚拟机接口
                String zettakitServer = Global.getConfig("zettakit.server");
                String zettakitLoginUrl = zettakitServer + "/api/login";
                String zettakitEditUrl = zettakitServer + "/api/compute/servers";
                // 调用登录获取token_id
                Map<String, Object> loginParams = new HashMap<String, Object>();
                loginParams.put("username", "admin");
                loginParams.put("password", "admin_pass");
                Map<String, Object> loginResult = HttpClientUtil.post(zettakitLoginUrl, loginParams);
                //Double status = (Double) mapResult.get("status");
                String loginMsg = (String) loginResult.get("msg");
                if ("success".equals(loginMsg)) {
                    Map tokenMap = (Map) loginResult.get("data");
                    String token_id = (String) tokenMap.get("token_id");
                    // 调用创建接口地址
                    // 获取参数
                    String zettakitImageId = Global.getConfig("zettakit.imageId");
                    String zettakitFlavorId = Global.getConfig("zettakit.flavorId");
                    String zettakitNetId = Global.getConfig("zettakit.netId");
                    int zettakitTemplateId = Integer.valueOf(Global.getConfig("zettakit.templateId"));
                    List<Map> nics = new ArrayList<Map>();
                    Map nic = new HashMap();
                    nic.put("net-id", zettakitNetId);
                    nic.put("v4-fixed-ip", "");
                    nics.add(nic);
                    Map<String, Object> editParams = new HashMap<String, Object>();
                    // 名称取登录名即身份证号
                    editParams.put("name", UserUtils.getUser().getLoginName());
                    editParams.put("image", zettakitImageId);
                    editParams.put("flavor", zettakitFlavorId);
                    editParams.put("key_name", "");
                    editParams.put("nics", nics);
                    editParams.put("instance_count", 1);
                    editParams.put("template_id", zettakitTemplateId);
                    Map<String, Object> editResult = HttpClientUtil.post(zettakitEditUrl, editParams, null, token_id);
                    String editMsg = (String) editResult.get("msg");
                    if ("success".equals(editMsg)) { // 创建成功
                        bizVmApply.setCheckFlag("2");
                        bizVmApply.setCheckId("sys");
                        bizVmApply.setCheckName("系统");
                        bizVmApply.setCheckDate(new Date());
                    } else if ("资源不足".equals(editMsg)) {
                        bizVmApply.setCheckFlag("3");
                        bizVmApply.setCheckReason("平台资源不足，请联系管理员！");
                        bizVmApply.setCheckId("sys");
                        bizVmApply.setCheckName("系统");
                        bizVmApply.setCheckDate(new Date());
                    }
                }
            }
        }
        User user = UserUtils.getUser();
        bizVmApply.setApplyId(user.getId());
        bizVmApply.setApplyIdCard(user.getLoginName() == null ? "" : user.getLoginName());
        bizVmApply.setApplyName(user.getName() == null ? "" : user.getName());
        bizVmApplyService.save(bizVmApply);

        String origin = request.getParameter("origin");
        if (("front").equals(origin)) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            Menu menu = UserUtils.getNavMenu("myapply");
            model.addAttribute("menu", menu);
            model.addAttribute("checkFlag", "");
            addMessage(redirectAttributes, "提交虚拟机使用申请成功");
            return "redirect:" + Global.getAdminPath() + "/biz/bizVmApply/list?origin=front";
        } else {
            addMessage(redirectAttributes, "保存虚拟机使用申请成功");
            return "redirect:" + Global.getAdminPath() + "/biz/bizVmApply/?repage";
        }
    }

    @RequiresPermissions("biz:bizVmApply:edit")
    @RequestMapping(value = "delete")
    public String delete(BizVmApply bizVmApply, HttpServletRequest request, RedirectAttributes redirectAttributes, Model model) {
        String origin = request.getParameter("origin");
        bizVmApplyService.delete(bizVmApply);
        if (("front").equals(origin)) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            Menu menu = UserUtils.getNavMenu("myapply");
            model.addAttribute("menu", menu);
            addMessage(redirectAttributes, "删除虚拟机使用申请成功");
            return "redirect:" + Global.getAdminPath() + "/biz/bizVmApply/list?origin=front";
        } else {
            addMessage(redirectAttributes, "删除虚拟机使用申请成功");
            return "redirect:" + Global.getAdminPath() + "/biz/bizVmApply/?repage";
        }
    }

    /**
     * 后台审核方法
     */
    @RequestMapping(value = "check")
    public String check(BizVmApply bizVmApply, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        if (!beanValidator(model, bizVmApply)) {
            return form(bizVmApply, model, request);
        }
        User user = UserUtils.getUser();
        bizVmApply.setCheckId(user.getId());
        bizVmApply.setCheckName(user.getName() == null ? "" : user.getName());
        bizVmApply.setCheckDate(new Date());
        bizVmApplyService.save(bizVmApply);
        addMessage(redirectAttributes, "审核虚拟机使用申请成功");
        return "redirect:" + Global.getAdminPath() + "/biz/bizVmApply/?repage";
    }
}